using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Data;
using VintaSoft.Twain;
using Dimok;

namespace ScanStation {
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class MainForm : System.Windows.Forms.Form {
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.ComboBox comboSources;
		private System.Windows.Forms.CheckBox chkShowUI;
		private System.Windows.Forms.CheckBox chkDisableAfterAcq;
		private System.Windows.Forms.CheckBox chkAutoCleanBuffer;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.TextBox imagesCounter;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.TextBox maxImages;
		private System.Windows.Forms.Button BPrev;
		private System.Windows.Forms.Button BNext;
		private System.Windows.Forms.PictureBox pictureBox1;
		private System.Windows.Forms.Label labelImgNum;
		private IContainer components;

		private bool flagDeviceWork;
		private System.Windows.Forms.Button BSaveImage;
		private System.Windows.Forms.Button BUploadImage;
		private System.Windows.Forms.SaveFileDialog saveFileDialog1;
		private System.Windows.Forms.Panel panel1;
		private System.Windows.Forms.CheckBox chkModalUI;
		public VintaSoft.Twain.VSTwain VSTwain1;
		private System.Windows.Forms.Button BStartStop;
		private System.Windows.Forms.Button BAcquire;
		private System.Windows.Forms.Button BSelectSource;
		private System.Windows.Forms.Button BGetSourceInfo;
		private System.Windows.Forms.Button BDeleteImage;
		private System.Windows.Forms.ProgressBar progressBar1;
		private System.Windows.Forms.Label txtAction;
		private System.Windows.Forms.Button BProcessImage;
		private System.Windows.Forms.Button BRotateImage;
		private FolderBrowserDialog fbd;
		private TextBox txtBarCode;
		private System.Windows.Forms.Timer timer1;
		private Label lblBarCodesHeader;
		private TextBox txtTolerance;
		private Label label4;
		private Button btnStop;
		private System.Windows.Forms.Timer timerSetControls;
		private Button btnClearImages;
		private Button btnSaveTo;
		private TextBox txtSaveTo;
		private TextBox lblBarCodes;
		private DateTimePicker pmDate;
		private Label lblPMDate;
		private System.Windows.Forms.Timer timerBarCodeBox;
		private System.Windows.Forms.Timer timerStopScanner;
		private CheckBox chkCopyBarCode;
		public int imageNum;

		public MainForm() {
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//

			//CheckForIllegalCrossThreadCalls = false;

			VSTwain1 = new VintaSoft.Twain.VSTwain();
			VSTwain1.Register("Dmitri Lapchine", "dl@wonderlend.com", "idm67lLbnOGTRvxx/6Q/Zjtzkf/tHEkiC/cUkTY7LyDb2UxspdqEAX/A/cD7HfyKg74UXCGJKHsZCeodHEH++/r1qwvzhbB37Psa304Zi5GGx3/GyyNMikw5Go4KSGxyFikfNUZypUHkBdV1Ts4gpbFIFe3OPiwjYbxnnewOwRr8");
			VSTwain1.maxImages = 10;
			VSTwain1.PostScan += new VintaSoft.Twain.VSTwain.PostScanEventHandler(VSTwain1_PostScanEvent);
			VSTwain1.Progress += new VintaSoft.Twain.VSTwain.ProgressEventHandler(ImageProcessing_Progress);
			flagDeviceWork = false;
			imageNum = -1;
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose(bool disposing) {
			if(disposing) {
				if(components != null) {
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent() {
			this.components = new System.ComponentModel.Container();
			this.BStartStop = new System.Windows.Forms.Button();
			this.BAcquire = new System.Windows.Forms.Button();
			this.BSelectSource = new System.Windows.Forms.Button();
			this.label1 = new System.Windows.Forms.Label();
			this.comboSources = new System.Windows.Forms.ComboBox();
			this.chkShowUI = new System.Windows.Forms.CheckBox();
			this.chkDisableAfterAcq = new System.Windows.Forms.CheckBox();
			this.chkAutoCleanBuffer = new System.Windows.Forms.CheckBox();
			this.label2 = new System.Windows.Forms.Label();
			this.imagesCounter = new System.Windows.Forms.TextBox();
			this.label3 = new System.Windows.Forms.Label();
			this.maxImages = new System.Windows.Forms.TextBox();
			this.BPrev = new System.Windows.Forms.Button();
			this.BNext = new System.Windows.Forms.Button();
			this.pictureBox1 = new System.Windows.Forms.PictureBox();
			this.labelImgNum = new System.Windows.Forms.Label();
			this.BGetSourceInfo = new System.Windows.Forms.Button();
			this.BSaveImage = new System.Windows.Forms.Button();
			this.BUploadImage = new System.Windows.Forms.Button();
			this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
			this.chkModalUI = new System.Windows.Forms.CheckBox();
			this.panel1 = new System.Windows.Forms.Panel();
			this.BDeleteImage = new System.Windows.Forms.Button();
			this.BProcessImage = new System.Windows.Forms.Button();
			this.progressBar1 = new System.Windows.Forms.ProgressBar();
			this.txtAction = new System.Windows.Forms.Label();
			this.BRotateImage = new System.Windows.Forms.Button();
			this.fbd = new System.Windows.Forms.FolderBrowserDialog();
			this.txtBarCode = new System.Windows.Forms.TextBox();
			this.timer1 = new System.Windows.Forms.Timer(this.components);
			this.lblBarCodesHeader = new System.Windows.Forms.Label();
			this.txtTolerance = new System.Windows.Forms.TextBox();
			this.label4 = new System.Windows.Forms.Label();
			this.btnStop = new System.Windows.Forms.Button();
			this.timerSetControls = new System.Windows.Forms.Timer(this.components);
			this.btnClearImages = new System.Windows.Forms.Button();
			this.btnSaveTo = new System.Windows.Forms.Button();
			this.txtSaveTo = new System.Windows.Forms.TextBox();
			this.lblBarCodes = new System.Windows.Forms.TextBox();
			this.pmDate = new System.Windows.Forms.DateTimePicker();
			this.lblPMDate = new System.Windows.Forms.Label();
			this.timerBarCodeBox = new System.Windows.Forms.Timer(this.components);
			this.timerStopScanner = new System.Windows.Forms.Timer(this.components);
			this.chkCopyBarCode = new System.Windows.Forms.CheckBox();
			((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
			this.SuspendLayout();
			// 
			// BStartStop
			// 
			this.BStartStop.Location = new System.Drawing.Point(8,8);
			this.BStartStop.Name = "BStartStop";
			this.BStartStop.Size = new System.Drawing.Size(144,32);
			this.BStartStop.TabIndex = 0;
			this.BStartStop.Text = "Start Device";
			this.BStartStop.Click += new System.EventHandler(this.BStartStop_Click);
			// 
			// BAcquire
			// 
			this.BAcquire.Enabled = false;
			this.BAcquire.Location = new System.Drawing.Point(8,48);
			this.BAcquire.Name = "BAcquire";
			this.BAcquire.Size = new System.Drawing.Size(144,32);
			this.BAcquire.TabIndex = 1;
			this.BAcquire.Text = "Acquire";
			this.BAcquire.Click += new System.EventHandler(this.BAcquire_Click);
			// 
			// BSelectSource
			// 
			this.BSelectSource.Enabled = false;
			this.BSelectSource.Location = new System.Drawing.Point(8,88);
			this.BSelectSource.Name = "BSelectSource";
			this.BSelectSource.Size = new System.Drawing.Size(144,32);
			this.BSelectSource.TabIndex = 2;
			this.BSelectSource.Text = "Select Source";
			this.BSelectSource.Click += new System.EventHandler(this.BSelectSource_Click);
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(168,8);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(56,16);
			this.label1.TabIndex = 3;
			this.label1.Text = "Sources:";
			// 
			// comboSources
			// 
			this.comboSources.Enabled = false;
			this.comboSources.Location = new System.Drawing.Point(216,8);
			this.comboSources.Name = "comboSources";
			this.comboSources.Size = new System.Drawing.Size(256,21);
			this.comboSources.TabIndex = 4;
			this.comboSources.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
			// 
			// chkShowUI
			// 
			this.chkShowUI.Enabled = false;
			this.chkShowUI.Location = new System.Drawing.Point(168,32);
			this.chkShowUI.Name = "chkShowUI";
			this.chkShowUI.Size = new System.Drawing.Size(72,16);
			this.chkShowUI.TabIndex = 5;
			this.chkShowUI.Text = "Show UI";
			this.chkShowUI.CheckedChanged += new System.EventHandler(this.chkShowUI_CheckedChanged);
			// 
			// chkDisableAfterAcq
			// 
			this.chkDisableAfterAcq.Enabled = false;
			this.chkDisableAfterAcq.Location = new System.Drawing.Point(168,48);
			this.chkDisableAfterAcq.Name = "chkDisableAfterAcq";
			this.chkDisableAfterAcq.Size = new System.Drawing.Size(136,16);
			this.chkDisableAfterAcq.TabIndex = 6;
			this.chkDisableAfterAcq.Text = "Disable After Acquire";
			this.chkDisableAfterAcq.CheckedChanged += new System.EventHandler(this.chkDisableAfterAcq_CheckedChanged);
			// 
			// chkAutoCleanBuffer
			// 
			this.chkAutoCleanBuffer.AutoSize = true;
			this.chkAutoCleanBuffer.Enabled = false;
			this.chkAutoCleanBuffer.Location = new System.Drawing.Point(168,104);
			this.chkAutoCleanBuffer.Name = "chkAutoCleanBuffer";
			this.chkAutoCleanBuffer.Size = new System.Drawing.Size(271,17);
			this.chkAutoCleanBuffer.TabIndex = 7;
			this.chkAutoCleanBuffer.Text = "Images buffer will be cleared automatically if it be full";
			this.chkAutoCleanBuffer.CheckedChanged += new System.EventHandler(this.chkAutoCleanBuffer_CheckedChanged);
			// 
			// label2
			// 
			this.label2.AutoSize = true;
			this.label2.Location = new System.Drawing.Point(168,68);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(44,13);
			this.label2.TabIndex = 8;
			this.label2.Text = "Images:";
			// 
			// imagesCounter
			// 
			this.imagesCounter.Enabled = false;
			this.imagesCounter.Location = new System.Drawing.Point(170,82);
			this.imagesCounter.Name = "imagesCounter";
			this.imagesCounter.ReadOnly = true;
			this.imagesCounter.Size = new System.Drawing.Size(38,20);
			this.imagesCounter.TabIndex = 9;
			// 
			// label3
			// 
			this.label3.AutoSize = true;
			this.label3.Location = new System.Drawing.Point(210,68);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(66,13);
			this.label3.TabIndex = 10;
			this.label3.Text = "Max images:";
			// 
			// maxImages
			// 
			this.maxImages.Enabled = false;
			this.maxImages.Location = new System.Drawing.Point(213,82);
			this.maxImages.Name = "maxImages";
			this.maxImages.Size = new System.Drawing.Size(56,20);
			this.maxImages.TabIndex = 11;
			this.maxImages.TextChanged += new System.EventHandler(this.maxImages_TextChanged);
			// 
			// BPrev
			// 
			this.BPrev.Enabled = false;
			this.BPrev.Location = new System.Drawing.Point(8,136);
			this.BPrev.Name = "BPrev";
			this.BPrev.Size = new System.Drawing.Size(96,23);
			this.BPrev.TabIndex = 12;
			this.BPrev.Text = "Previous image";
			this.BPrev.Click += new System.EventHandler(this.BPrev_Click);
			// 
			// BNext
			// 
			this.BNext.Enabled = false;
			this.BNext.Location = new System.Drawing.Point(376,136);
			this.BNext.Name = "BNext";
			this.BNext.Size = new System.Drawing.Size(96,23);
			this.BNext.TabIndex = 13;
			this.BNext.Text = "Next image";
			this.BNext.Click += new System.EventHandler(this.BNext_Click);
			// 
			// pictureBox1
			// 
			this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
									| System.Windows.Forms.AnchorStyles.Left)
									| System.Windows.Forms.AnchorStyles.Right)));
			this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
			this.pictureBox1.Location = new System.Drawing.Point(8,184);
			this.pictureBox1.Name = "pictureBox1";
			this.pictureBox1.Size = new System.Drawing.Size(360,507);
			this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
			this.pictureBox1.TabIndex = 14;
			this.pictureBox1.TabStop = false;
			// 
			// labelImgNum
			// 
			this.labelImgNum.Location = new System.Drawing.Point(128,165);
			this.labelImgNum.Name = "labelImgNum";
			this.labelImgNum.Size = new System.Drawing.Size(224,16);
			this.labelImgNum.TabIndex = 15;
			this.labelImgNum.Text = "No images";
			this.labelImgNum.TextAlign = System.Drawing.ContentAlignment.TopCenter;
			// 
			// BGetSourceInfo
			// 
			this.BGetSourceInfo.Enabled = false;
			this.BGetSourceInfo.Location = new System.Drawing.Point(478,6);
			this.BGetSourceInfo.Name = "BGetSourceInfo";
			this.BGetSourceInfo.Size = new System.Drawing.Size(128,23);
			this.BGetSourceInfo.TabIndex = 17;
			this.BGetSourceInfo.Text = "Get source info";
			this.BGetSourceInfo.Click += new System.EventHandler(this.BGetSourceInfo_Click);
			// 
			// BSaveImage
			// 
			this.BSaveImage.Enabled = false;
			this.BSaveImage.Location = new System.Drawing.Point(112,136);
			this.BSaveImage.Name = "BSaveImage";
			this.BSaveImage.Size = new System.Drawing.Size(72,23);
			this.BSaveImage.TabIndex = 18;
			this.BSaveImage.Text = "Save image";
			this.BSaveImage.Click += new System.EventHandler(this.BSaveImage_Click);
			// 
			// BUploadImage
			// 
			this.BUploadImage.Enabled = false;
			this.BUploadImage.Location = new System.Drawing.Point(192,136);
			this.BUploadImage.Name = "BUploadImage";
			this.BUploadImage.Size = new System.Drawing.Size(88,23);
			this.BUploadImage.TabIndex = 19;
			this.BUploadImage.Text = "Upload image";
			// 
			// saveFileDialog1
			// 
			this.saveFileDialog1.FileName = "doc1";
			// 
			// chkModalUI
			// 
			this.chkModalUI.Enabled = false;
			this.chkModalUI.Location = new System.Drawing.Point(240,32);
			this.chkModalUI.Name = "chkModalUI";
			this.chkModalUI.Size = new System.Drawing.Size(72,16);
			this.chkModalUI.TabIndex = 20;
			this.chkModalUI.Text = "Modal UI";
			this.chkModalUI.CheckedChanged += new System.EventHandler(this.chkModalUI_CheckedChanged);
			// 
			// panel1
			// 
			this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
			this.panel1.Location = new System.Drawing.Point(8,128);
			this.panel1.Name = "panel1";
			this.panel1.Size = new System.Drawing.Size(566,1);
			this.panel1.TabIndex = 21;
			// 
			// BDeleteImage
			// 
			this.BDeleteImage.Enabled = false;
			this.BDeleteImage.Location = new System.Drawing.Point(288,135);
			this.BDeleteImage.Name = "BDeleteImage";
			this.BDeleteImage.Size = new System.Drawing.Size(80,24);
			this.BDeleteImage.TabIndex = 24;
			this.BDeleteImage.Text = "Delete image";
			this.BDeleteImage.Click += new System.EventHandler(this.BDeleteImage_Click);
			// 
			// BProcessImage
			// 
			this.BProcessImage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
			this.BProcessImage.Enabled = false;
			this.BProcessImage.Location = new System.Drawing.Point(8,709);
			this.BProcessImage.Name = "BProcessImage";
			this.BProcessImage.Size = new System.Drawing.Size(128,40);
			this.BProcessImage.TabIndex = 25;
			this.BProcessImage.Text = "Despeckle => deskew => detect border";
			this.BProcessImage.Click += new System.EventHandler(this.BProcessImage_Click);
			// 
			// progressBar1
			// 
			this.progressBar1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
									| System.Windows.Forms.AnchorStyles.Right)));
			this.progressBar1.Location = new System.Drawing.Point(144,710);
			this.progressBar1.Name = "progressBar1";
			this.progressBar1.Size = new System.Drawing.Size(447,23);
			this.progressBar1.TabIndex = 26;
			// 
			// txtAction
			// 
			this.txtAction.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
									| System.Windows.Forms.AnchorStyles.Right)));
			this.txtAction.Location = new System.Drawing.Point(152,733);
			this.txtAction.Name = "txtAction";
			this.txtAction.Size = new System.Drawing.Size(431,16);
			this.txtAction.TabIndex = 27;
			// 
			// BRotateImage
			// 
			this.BRotateImage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
			this.BRotateImage.Enabled = false;
			this.BRotateImage.Location = new System.Drawing.Point(602,710);
			this.BRotateImage.Name = "BRotateImage";
			this.BRotateImage.Size = new System.Drawing.Size(48,39);
			this.BRotateImage.TabIndex = 28;
			this.BRotateImage.Text = "Rotate image";
			this.BRotateImage.Click += new System.EventHandler(this.BRotateImage_Click);
			// 
			// txtBarCode
			// 
			this.txtBarCode.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.txtBarCode.Location = new System.Drawing.Point(376,222);
			this.txtBarCode.Name = "txtBarCode";
			this.txtBarCode.Size = new System.Drawing.Size(270,20);
			this.txtBarCode.TabIndex = 29;
			this.txtBarCode.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.txtBarCode_PreviewKeyDown);
			this.txtBarCode.Leave += new System.EventHandler(this.txtBarCode_Leave);
			this.txtBarCode.Validated += new System.EventHandler(this.txtBarCode_Validated);
			// 
			// timer1
			// 
			this.timer1.Interval = 300;
			this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
			// 
			// lblBarCodesHeader
			// 
			this.lblBarCodesHeader.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.lblBarCodesHeader.AutoSize = true;
			this.lblBarCodesHeader.Location = new System.Drawing.Point(374,206);
			this.lblBarCodesHeader.Name = "lblBarCodesHeader";
			this.lblBarCodesHeader.Size = new System.Drawing.Size(56,13);
			this.lblBarCodesHeader.TabIndex = 30;
			this.lblBarCodesHeader.Text = "BarCodes:";
			// 
			// txtTolerance
			// 
			this.txtTolerance.Location = new System.Drawing.Point(279,82);
			this.txtTolerance.Name = "txtTolerance";
			this.txtTolerance.Size = new System.Drawing.Size(47,20);
			this.txtTolerance.TabIndex = 31;
			this.txtTolerance.Text = "40";
			// 
			// label4
			// 
			this.label4.AutoSize = true;
			this.label4.Location = new System.Drawing.Point(275,68);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(58,13);
			this.label4.TabIndex = 10;
			this.label4.Text = "Tolerance:";
			// 
			// btnStop
			// 
			this.btnStop.Location = new System.Drawing.Point(413,80);
			this.btnStop.Name = "btnStop";
			this.btnStop.Size = new System.Drawing.Size(75,23);
			this.btnStop.TabIndex = 32;
			this.btnStop.Text = "Crop";
			this.btnStop.UseVisualStyleBackColor = true;
			this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
			// 
			// timerSetControls
			// 
			this.timerSetControls.Interval = 300;
			this.timerSetControls.Tick += new System.EventHandler(this.timerSetControls_Tick);
			// 
			// btnClearImages
			// 
			this.btnClearImages.Location = new System.Drawing.Point(478,136);
			this.btnClearImages.Name = "btnClearImages";
			this.btnClearImages.Size = new System.Drawing.Size(96,23);
			this.btnClearImages.TabIndex = 13;
			this.btnClearImages.Text = "Clear Images";
			this.btnClearImages.Click += new System.EventHandler(this.btnClearImages_Click);
			// 
			// btnSaveTo
			// 
			this.btnSaveTo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.btnSaveTo.Location = new System.Drawing.Point(577,41);
			this.btnSaveTo.Name = "btnSaveTo";
			this.btnSaveTo.Size = new System.Drawing.Size(73,23);
			this.btnSaveTo.TabIndex = 13;
			this.btnSaveTo.Text = "Save To";
			this.btnSaveTo.Click += new System.EventHandler(this.btnSaveTo_Click);
			// 
			// txtSaveTo
			// 
			this.txtSaveTo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
									| System.Windows.Forms.AnchorStyles.Right)));
			this.txtSaveTo.Font = new System.Drawing.Font("Microsoft Sans Serif",6.75F,System.Drawing.FontStyle.Regular,System.Drawing.GraphicsUnit.Point,((byte)(0)));
			this.txtSaveTo.Location = new System.Drawing.Point(313,41);
			this.txtSaveTo.Name = "txtSaveTo";
			this.txtSaveTo.Size = new System.Drawing.Size(258,18);
			this.txtSaveTo.TabIndex = 33;
			this.txtSaveTo.ControlAdded += new System.Windows.Forms.ControlEventHandler(this.txtSaveTo_ControlAdded);
			this.txtSaveTo.TextChanged += new System.EventHandler(this.txtSaveTo_TextChanged);
			// 
			// lblBarCodes
			// 
			this.lblBarCodes.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.lblBarCodes.BackColor = System.Drawing.SystemColors.Menu;
			this.lblBarCodes.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
			this.lblBarCodes.Location = new System.Drawing.Point(376,249);
			this.lblBarCodes.Multiline = true;
			this.lblBarCodes.Name = "lblBarCodes";
			this.lblBarCodes.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
			this.lblBarCodes.Size = new System.Drawing.Size(269,247);
			this.lblBarCodes.TabIndex = 34;
			// 
			// pmDate
			// 
			this.pmDate.Format = System.Windows.Forms.DateTimePickerFormat.Short;
			this.pmDate.Location = new System.Drawing.Point(456,184);
			this.pmDate.Name = "pmDate";
			this.pmDate.Size = new System.Drawing.Size(98,20);
			this.pmDate.TabIndex = 35;
			// 
			// lblPMDate
			// 
			this.lblPMDate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.lblPMDate.AutoSize = true;
			this.lblPMDate.Location = new System.Drawing.Point(373,188);
			this.lblPMDate.Name = "lblPMDate";
			this.lblPMDate.Size = new System.Drawing.Size(77,13);
			this.lblPMDate.TabIndex = 30;
			this.lblPMDate.Text = "Postmark Date";
			// 
			// timerBarCodeBox
			// 
			this.timerBarCodeBox.Enabled = true;
			this.timerBarCodeBox.Interval = 1000;
			this.timerBarCodeBox.Tick += new System.EventHandler(this.timerBarCodeBox_Tick);
			// 
			// timerStopScanner
			// 
			this.timerStopScanner.Interval = 20000;
			this.timerStopScanner.Tick += new System.EventHandler(this.timerStopScanner_Tick);
			// 
			// chkCopyBarCode
			// 
			this.chkCopyBarCode.AutoSize = true;
			this.chkCopyBarCode.Location = new System.Drawing.Point(377,502);
			this.chkCopyBarCode.Name = "chkCopyBarCode";
			this.chkCopyBarCode.Size = new System.Drawing.Size(112,17);
			this.chkCopyBarCode.TabIndex = 36;
			this.chkCopyBarCode.Text = "BarCode is a copy";
			this.chkCopyBarCode.UseVisualStyleBackColor = true;
			// 
			// MainForm
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5,13);
			this.ClientSize = new System.Drawing.Size(657,774);
			this.Controls.Add(this.chkCopyBarCode);
			this.Controls.Add(this.pmDate);
			this.Controls.Add(this.lblBarCodes);
			this.Controls.Add(this.txtSaveTo);
			this.Controls.Add(this.btnStop);
			this.Controls.Add(this.txtTolerance);
			this.Controls.Add(this.txtBarCode);
			this.Controls.Add(this.BRotateImage);
			this.Controls.Add(this.txtAction);
			this.Controls.Add(this.progressBar1);
			this.Controls.Add(this.BProcessImage);
			this.Controls.Add(this.BDeleteImage);
			this.Controls.Add(this.panel1);
			this.Controls.Add(this.chkModalUI);
			this.Controls.Add(this.BUploadImage);
			this.Controls.Add(this.BSaveImage);
			this.Controls.Add(this.BGetSourceInfo);
			this.Controls.Add(this.labelImgNum);
			this.Controls.Add(this.pictureBox1);
			this.Controls.Add(this.btnSaveTo);
			this.Controls.Add(this.btnClearImages);
			this.Controls.Add(this.BNext);
			this.Controls.Add(this.BPrev);
			this.Controls.Add(this.maxImages);
			this.Controls.Add(this.label4);
			this.Controls.Add(this.label3);
			this.Controls.Add(this.imagesCounter);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.chkAutoCleanBuffer);
			this.Controls.Add(this.chkDisableAfterAcq);
			this.Controls.Add(this.chkShowUI);
			this.Controls.Add(this.comboSources);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.BSelectSource);
			this.Controls.Add(this.BAcquire);
			this.Controls.Add(this.BStartStop);
			this.Controls.Add(this.lblPMDate);
			this.Controls.Add(this.lblBarCodesHeader);
			this.Name = "MainForm";
			this.Text = "Scan Station";
			this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing);
			this.Load += new System.EventHandler(this.MainForm_Load);
			((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
			this.ResumeLayout(false);
			this.PerformLayout();

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() {
			try {
				Application.Run(new MainForm());
			} catch(Exception exc) {
				MessageBox.Show(exc.ToString());
			}
		}

		private void BStartStop_Click(object sender, System.EventArgs e) {
			if(pictureBox1.Image != null) {
				pictureBox1.Image.Dispose();
				pictureBox1.Image = null;
			}

			if(flagDeviceWork) {
				flagDeviceWork = false;
				VSTwain1.StopDevice();
				comboSources.Items.Clear();
				BStartStop.Text = "Start Device";
				timer1.Stop();
				if(pictureBox1.Image != null) {
					pictureBox1.Image.Dispose();
					pictureBox1.Image = null;
				}
				timerStopScanner.Stop();
			} else {
				flagDeviceWork = true;
				VSTwain1.StartDevice();
				chkShowUI.Checked = VSTwain1.showUI;
				chkModalUI.Checked = VSTwain1.modalUI;
				chkDisableAfterAcq.Checked = VSTwain1.disableAfterAcquire;
				chkAutoCleanBuffer.Checked = VSTwain1.autoCleanBuffer;
				comboSources.Items.Clear();
				for(int i = 0; i < VSTwain1.sourcesCount; i++) {
					comboSources.Items.Add(VSTwain1.GetSourceProductName(i));
				}
				comboSources.SelectedIndex = VSTwain1.sourceIndex;
				BStartStop.Text = "Stop Device";
				InitScanner_Start();
				timer1.Start();
				timerStopScanner.Enabled = true; timerStopScanner.Start();
			}

			BAcquire.Enabled = flagDeviceWork;
			BSelectSource.Enabled = flagDeviceWork;
			BGetSourceInfo.Enabled = flagDeviceWork;
			chkShowUI.Enabled = flagDeviceWork;
			chkModalUI.Enabled = flagDeviceWork;
			chkDisableAfterAcq.Enabled = flagDeviceWork;
			chkAutoCleanBuffer.Enabled = flagDeviceWork;
			imagesCounter.Enabled = flagDeviceWork;
			maxImages.Enabled = flagDeviceWork;
			comboSources.Enabled = flagDeviceWork;

			labelImgNum.Text = "No images";
			imagesCounter.Text = VSTwain1.numImages.ToString();
			maxImages.Text = VSTwain1.maxImages.ToString();
			BPrev.Enabled = false;
			BNext.Enabled = false;
			BSaveImage.Enabled = false;
			BUploadImage.Enabled = false;
			BDeleteImage.Enabled = false;
			BProcessImage.Enabled = false;
			BRotateImage.Enabled = false;
			imageNum = 0;
		}

		private void BAcquire_Click(object sender, System.EventArgs e) {
			InitScanner_Start();
		}
		private void InitScanner_Start() {
			new Thread(new ThreadStart(InitScanner)).Start();
		}
		private void InitScanner(){
			VSTwain1.OpenDataSource();
			VSTwain1.showUI = false;
			VSTwain1.disableAfterAcquire = true;
			VSTwain1.maxImages = 10;
			VSTwain1.autoCleanBuffer = true;
			VSTwain1.pixelType = PixelType.BW;
			VSTwain1.resolution = 300;

			VSTwain1.capability = (int)Capability.IAutomaticDeskew;
			VSTwain1.capType = CapType.OneValue;
			VSTwain1.capValue = 0;
			VSTwain1.SetCap();

			VSTwain1.capability = (int)Capability.IXResolution;
			VSTwain1.capType = CapType.OneValue;
			VSTwain1.capValue = 300;
			VSTwain1.SetCap();

			VSTwain1.unitOfMeasure = UnitOfMeasure.Inches;
			VSTwain1.tiffMultiPage = true;
			VSTwain1.tiffCompression = TiffCompression.None;

			if( VSTwain1.feederPresent ){
        VSTwain1.feederEnabled = true;
        VSTwain1.xferCount = -1;
        VSTwain1.autoFeed = true;
			}
			if(!VSTwain1.feederLoaded) {
				timer1.Start();
				timerStopScanner.Start();
			}
		}

		private void timer1_Tick(object sender,EventArgs e) {
			if(VSTwain1 == null) return;
			if(VSTwain1.dataSourceState == DataSourceState.Closed) return;
			if(VSTwain1.dataSourceState == DataSourceState.Working) return;
			if(VSTwain1.feederLoaded) {
				timer1.Stop();
				VSTwain1.pixelType = PixelType.GRAY;
				VSTwain1.resolution = 300;
				VSTwain1.Acquire();
			} else {
				return;
				VSTwain1.OpenDataSource();
				VSTwain1.capability = (int)Capability.FeedPage;
				VSTwain1.capType = CapType.OneValue;
				VSTwain1.capValue = 1;
				bool res = VSTwain1.SetCap();
				if(!res && VSTwain1.errorCode != 1) MessageBox.Show(VSTwain1.errorString+"("+VSTwain1.errorCode+")");
			}
		}

		private void VSTwain1_PostScanEvent(object sender,VintaSoft.Twain.PostScanEventArgs e) {
			timerStopScanner.Stop(); timerStopScanner.Start();
			if(!e.Flag) {
				if(VSTwain1.errorCode != 0)
					MessageBox.Show(VSTwain1.errorString);
			} else {
				MemoryStream ms = new MemoryStream();
				VSTwain1.GetCurrentImage().Save(ms,System.Drawing.Imaging.ImageFormat.Tiff);
				queImagesToBarCode.Enqueue(ms.ToArray());
				new Thread(new ThreadStart(ReadBarCodes)).Start();
				timerSetControls.Enabled = true;
				if(!VSTwain1.feederLoaded) {
					VSTwain1.OpenDataSource();
					VSTwain1.feederEnabled = true;
					timer1.Start();
				}
			}
		}
		private void timerSetControls_Tick(object sender,EventArgs e) {
			if(VSTwain1.dataSourceState == DataSourceState.Working) return;
			timerSetControls.Enabled = false;
			int i = VSTwain1.numImages;
			imagesCounter.Text = i.ToString();
			imageNum = i - 1;
			if(pictureBox1.Image != null) {
				pictureBox1.Image.Dispose();
				pictureBox1.Image = null;
			}
			pictureBox1.Image = VSTwain1.GetCurrentImage();
			SetText(labelImgNum,"Image " + imageNum.ToString() + " (" + VSTwain1.GetImageWidth(imageNum).ToString() + " x " + VSTwain1.GetImageHeight(imageNum).ToString() + " x " + VSTwain1.GetImageBPP(imageNum).ToString() + " bpp)");
			if(imageNum > 0) BPrev.Enabled = true;
			BSaveImage.Enabled = true;
			BUploadImage.Enabled = true;
			BDeleteImage.Enabled = true;
			BProcessImage.Enabled = true;
			BRotateImage.Enabled = true;
		}

		#region AutoCrop
		bool DoAutoCrop {
			get {
				VSTwain1.capability = (int)Capability.IAutomaticBorderDetection;
				return !VSTwain1.IsCapSupported();
			}
		}
		delegate void SetPictureCallback(Bitmap bm);
		void SetPictureImage(Bitmap bm) {
			if(pictureBox1.InvokeRequired) {
				SetPictureCallback d = new SetPictureCallback(SetPictureImage);
				pictureBox1.Invoke(d,bm);
			} else pictureBox1.Image = bm;
		}
		private void AutoCropStarter() {
			if(!DoAutoCrop) return;
			new Thread(new ThreadStart(AutoCrop)).Start();
		}
		private void AutoCrop() {
			try {
				VSTwain1.OpenDataSource();
				Thread.Sleep(500);
				SetPictureImage(AutoCrop(new Bitmap(pictureBox1.Image)).GetBitmap());
			} catch(Exception exc) {
				MessageBox.Show(this, exc.Message);
			}
		}
		private Atalasoft.Imaging.AtalaImage AutoCrop(Bitmap image) {
			Atalasoft.Imaging.AtalaImage file = Atalasoft.Imaging.AtalaImage.FromBitmap(image);
			Atalasoft.Imaging.ImageProcessing.AutoCropCommand acc = new Atalasoft.Imaging.ImageProcessing.AutoCropCommand();
			acc.UseMedianFilter = true;
			acc.Tolerance = int.Parse(txtTolerance.Text);
			file = new Atalasoft.Imaging.ImageProcessing.ChangePixelFormatCommand(Atalasoft.Imaging.PixelFormat.Pixel8bppGrayscale).ApplyToImage(file);
			Rectangle recBorders = acc.GetBorder(file);
			if(recBorders.Height < 10) { MessageBox.Show(this, "Page " + (VSTwain1.numImages + 1) + " was croped to " + recBorders + ". Page will be saved in full."); return file; }
			return new Atalasoft.Imaging.ImageProcessing.CropCommand(recBorders).ApplyToImage(file);
		}
		#endregion

		#region BarCodes
		private Dimok.BarCodes dsBarCodes = new Dimok.BarCodes();
		private Queue queImagesToBarCode = new Queue();
		private void ReadBarCodes() {
			SetEnabled(txtBarCode,false);
			//Atalasoft.Imaging.AtalaImage ai = Atalasoft.Imaging.AtalaImage.FromBitmap((Bitmap)VSTwain1.GetCurrentImage());
			//if( ai.PixelFormat != Atalasoft.Imaging.PixelFormat.Pixel8bppGrayscale ) 
			//	ai = new Atalasoft.Imaging.ImageProcessing.ChangePixelFormatCommand(Atalasoft.Imaging.PixelFormat.Pixel8bppGrayscale).ApplyToImage(ai);
			//Atalasoft.Barcoding.BarReader br = new Atalasoft.Barcoding.BarReader(ai);
			//Atalasoft.Barcoding.ReadOpts ro = new Atalasoft.Barcoding.ReadOpts();
			//ro.Direction = Atalasoft.Barcoding.Directions.East | Atalasoft.Barcoding.Directions.West | Atalasoft.Barcoding.Directions.North | Atalasoft.Barcoding.Directions.South;
			//ro.Symbology = Atalasoft.Barcoding.Symbologies.Codabar | Atalasoft.Barcoding.Symbologies.Code11 | Atalasoft.Barcoding.Symbologies.Code128 | Atalasoft.Barcoding.Symbologies.Code32 | Atalasoft.Barcoding.Symbologies.Code39 | Atalasoft.Barcoding.Symbologies.Code93 | Atalasoft.Barcoding.Symbologies.Ean13 | Atalasoft.Barcoding.Symbologies.Ean8 | Atalasoft.Barcoding.Symbologies.I2of5 | Atalasoft.Barcoding.Symbologies.RssLimited | Atalasoft.Barcoding.Symbologies.Telepen | Atalasoft.Barcoding.Symbologies.Upca | Atalasoft.Barcoding.Symbologies.Upce;
			//Atalasoft.Barcoding.BarCode[] bcs = br.ReadBars(ro);
			//Dimok.BarCodes.BarCodeDataTable dt = Dimok.BarCode.Read(ai.ToByteArray(new Atalasoft.Imaging.Codec.TiffEncoder()));
			try {
				Dimok.BarCodes.BarCodeDataTable dt = Dimok.BarCode.Read((byte[])queImagesToBarCode.Dequeue());
				//foreach(Atalasoft.Barcoding.BarCode bc in bcs)
				//	dt.AddBarCodeRow(bc.DataString,(int)bc.Symbology,bc.Symbology + "");
				dsBarCodes.Merge(dt);
			} catch(Exception exc) { MessageBox.Show(this,exc.ToString()); }
			SetText(lblBarCodes,dsBarCodes.GetXml());
			SetEnabled(txtBarCode,true);
			//AutoCropStarter();
		}

		delegate void SetTextCallback(Control c,string text);
		void SetText(Control c,string text) {
			if(c.InvokeRequired) {
				SetTextCallback d = new SetTextCallback(SetText);
				c.Invoke(d,c,text);
			} else c.Text = text;
		}
		delegate void SetEnableCallback(Control c,bool enabled);
		void SetEnabled(Control c,bool enabled) {
			if(c.InvokeRequired) {
				SetEnableCallback d = new SetEnableCallback(SetEnabled);
				c.Invoke(d,c,enabled);
			} else c.Enabled = enabled;
		}
		#endregion

		ScanStation.Properties.Settings Settings = new Properties.Settings();
		string SaveTo { 
			get { return new Properties.Settings().SaveTo; }
			set { txtSaveTo.Text = Settings.SaveTo = value; }
		}

		#region BSaveImage_Click
		private void BSaveImage_Click(object sender,System.EventArgs e) {
			if(VSTwain1.numImages == 0) return;
			this.Cursor = Cursors.WaitCursor;
			Application.DoEvents();
			Atalasoft.Imaging.Workspace ws = new Atalasoft.Imaging.Workspace();
			//WebSupergoo.ABCpdf5.Doc docAll = new WebSupergoo.ABCpdf5.Doc();
			string fileBase = SaveTo + "\\" + DateTime.Now.ToString("yyMMdd_HHmmss");
			string fileTemp = Path.GetTempFileName();
			for(int i = 0; i < VSTwain1.numImages; i++) {
				//WebSupergoo.ABCpdf5.Doc doc = new WebSupergoo.ABCpdf5.Doc();
				//doc.AddImage(new Bitmap(VSTwain1.GetImage(i)));
				//docAll.Append(doc);
				//Atalasoft.Imaging.AtalaImage file = Atalasoft.Imaging.AtalaImage.FromBitmap(new Bitmap(VSTwain1.GetImage(i)));
				//Atalasoft.Imaging.ImageProcessing.AutoCropCommand acc = new Atalasoft.Imaging.ImageProcessing.AutoCropCommand();
				//acc.UseMedianFilter = true;
				//acc.Tolerance = int.Parse(txtTolerance.Text);
				//file = new Atalasoft.Imaging.ImageProcessing.ChangePixelFormatCommand(Atalasoft.Imaging.PixelFormat.Pixel8bppGrayscale).ApplyToImage(file);
				//Rectangle recBorders = acc.GetBorder(new Atalasoft.Imaging.ImageProcessing.ChangePixelFormatCommand(Atalasoft.Imaging.PixelFormat.Pixel1bppIndexed).ApplyToImage(file));
				//if(recBorders.Height < 10) MessageBox.Show(this,"Page " + (i + 1) + " was croped to " + recBorders + ". Page will be saved in full.");
				//else file = new Atalasoft.Imaging.ImageProcessing.CropCommand(recBorders).ApplyToImage(file);
				//Bitmap bm = new Bitmap(VSTwain1.GetImage(i));
				//if(DoAutoCrop) ws.Images.Add(AutoCrop(bm));
				//else 
				ws.Images.Add(new Atalasoft.Imaging.ImageProcessing.ChangePixelFormatCommand(Atalasoft.Imaging.PixelFormat.Pixel8bppGrayscale).ApplyToImage(Atalasoft.Imaging.AtalaImage.FromBitmap((Bitmap)VSTwain1.GetImage(i))));
			}
			Atalasoft.Imaging.Codec.TiffEncoder ti = new Atalasoft.Imaging.Codec.TiffEncoder(Atalasoft.Imaging.Codec.TiffCompression.Group4FaxEncoding);
			ws.Save(fileTemp,ti);
			File.Move(fileTemp,fileBase + ".tif");
			dsBarCodes.BarCode.AddBarCodeRow(pmDate.Text,(int)BarCodeTypes.PostmarkDate,"PostmarkDate");
			dsBarCodes.BarCode.AddBarCodeRow(Environment.UserDomainName + "\\" + Environment.UserName, (int)BarCodeTypes.UserName, "UserName");
			dsBarCodes.BarCode.AddBarCodeRow(VSTwain1.numImages+"", (int)BarCodeTypes.PageCount, BarCodeTypes.PageCount+"");
			dsBarCodes.BarCode.AddBarCodeRow(chkCopyBarCode.Checked+"",(int)BarCodeTypes.BarCodeCopy,"BarCodeCopy");
			dsBarCodes.BarCode.AddBarCodeRow(Guid.NewGuid().ToString(),(int)BarCodeTypes.GUID,BarCodeTypes.GUID + "");
			File.WriteAllText(fileBase + ".bc",dsBarCodes.GetXml());
			ClearImages();
			SetControls();
			Cursor = Cursors.Default;
			return;
		}

		#endregion
		
		#region Controls

		void ClearImages() {
			dsBarCodes.BarCode.Clear();
			lblBarCodes.Text = dsBarCodes.GetXml();
			//System.Diagnostics.Process.Start(saveFileDialog1.FileName);
			while(VSTwain1.numImages > 0) VSTwain1.DeleteImage(0);
			timerSetControls.Enabled = true;
		}

		private void btnClearImages_Click(object sender,EventArgs e) {
			ClearImages();
		}

		private void BSelectSource_Click(object sender,System.EventArgs e) {
			VSTwain1.SelectSource();
			comboSources.SelectedIndex = VSTwain1.sourceIndex;
		}

		private void comboBox1_SelectedIndexChanged(object sender,System.EventArgs e) {
			VSTwain1.sourceIndex = comboSources.SelectedIndex;
		}

		private void chkShowUI_CheckedChanged(object sender,System.EventArgs e) {
			VSTwain1.showUI = chkShowUI.Checked;
			chkModalUI.Enabled = VSTwain1.showUI;
			chkDisableAfterAcq.Enabled = VSTwain1.showUI;
			if(!chkDisableAfterAcq.Enabled) {
				VSTwain1.disableAfterAcquire = true;
				chkDisableAfterAcq.Checked = true;
			}
		}

		private void chkModalUI_CheckedChanged(object sender,System.EventArgs e) {
			VSTwain1.modalUI = chkModalUI.Checked;
		}

		private void chkDisableAfterAcq_CheckedChanged(object sender,System.EventArgs e) {
			VSTwain1.disableAfterAcquire = chkDisableAfterAcq.Checked;
		}

		private void chkAutoCleanBuffer_CheckedChanged(object sender,System.EventArgs e) {
			VSTwain1.autoCleanBuffer = chkAutoCleanBuffer.Checked;
		}

		private void maxImages_TextChanged(object sender,System.EventArgs e) {
			VSTwain1.maxImages = int.Parse(maxImages.Text);
			BPrev.Enabled = false;
			BNext.Enabled = false;
			BProcessImage.Enabled = false;
			BRotateImage.Enabled = false;
			imagesCounter.Text = "0";
			labelImgNum.Text = "No images";
			imageNum = 0;
			if(pictureBox1.Image != null) {
				pictureBox1.Image.Dispose();
				pictureBox1.Image = null;
			}
		}

		private void BPrev_Click(object sender,System.EventArgs e) {
			int i = VSTwain1.numImages - 1;
			if((imageNum > 0) && (imageNum <= i)) {
				imageNum = imageNum - 1;
				labelImgNum.Text = "Image " + imageNum.ToString() + " (" + VSTwain1.GetImageWidth(imageNum).ToString() + " x " + VSTwain1.GetImageHeight(imageNum).ToString() + " x " + VSTwain1.GetImageBPP(imageNum).ToString() + " bpp)";
				if(pictureBox1.Image != null) {
					pictureBox1.Image.Dispose();
					pictureBox1.Image = null;
				}
				pictureBox1.Image = VSTwain1.GetImage(imageNum);
				AutoCropStarter();
			}
			if(imageNum == 0) BPrev.Enabled = false;
			if(i > imageNum) BNext.Enabled = true;
		}

		private void BNext_Click(object sender,System.EventArgs e) {
			int i = VSTwain1.numImages - 1;
			if(imageNum < i) {
				imageNum = imageNum + 1;
				labelImgNum.Text = "Image " + imageNum.ToString() + " (" + VSTwain1.GetImageWidth(imageNum).ToString() + " x " + VSTwain1.GetImageHeight(imageNum).ToString() + " x " + VSTwain1.GetImageBPP(imageNum).ToString() + " bpp)";
				if(pictureBox1.Image != null) {
					pictureBox1.Image.Dispose();
					pictureBox1.Image = null;
				}
				pictureBox1.Image = VSTwain1.GetImage(imageNum);
				AutoCropStarter();
			}
			if(imageNum == i) BNext.Enabled = false;
			if(imageNum > 0) BPrev.Enabled = true;
		}

		private void BGetSourceInfo_Click(object sender,System.EventArgs e) {
			DevCapsForm devCapsForm;
			devCapsForm = new DevCapsForm();
			devCapsForm.ShowDialog(this);
		}

		private void BDeleteImage_Click(object sender,System.EventArgs e) {
			if(VSTwain1.DeleteImage(imageNum)) {
				imagesCounter.Text = VSTwain1.numImages.ToString();
				if(imageNum >= VSTwain1.numImages) imageNum = VSTwain1.numImages - 1;
				if(pictureBox1.Image != null) {
					pictureBox1.Image.Dispose();
					pictureBox1.Image = null;
				}
				pictureBox1.Image = VSTwain1.GetImage(imageNum);
				SetControls();
			} else
				MessageBox.Show(VSTwain1.errorString);
		}

		#endregion

		#region SetControls
		void SetControls() {
			try {
				if(VSTwain1.numImages == 0) {
					labelImgNum.Text = "";
					BPrev.Enabled = false;
					BNext.Enabled = false;
					SetEnabled(BSaveImage,false);
					BUploadImage.Enabled = false;
					BDeleteImage.Enabled = false;
					BProcessImage.Enabled = false;
					BRotateImage.Enabled = false;
					chkCopyBarCode.Checked = false;
				} else {
					labelImgNum.Text = "Image " + imageNum.ToString() + " (" + VSTwain1.GetImageWidth(imageNum).ToString() + " x " + VSTwain1.GetImageHeight(imageNum).ToString() + " x " + VSTwain1.GetImageBPP(imageNum).ToString() + " bpp)";
					if(imageNum > 0) BPrev.Enabled = true;
					else BPrev.Enabled = false;
					if(imageNum == (VSTwain1.numImages - 1)) BNext.Enabled = false;
					else BNext.Enabled = true;
				}
			} catch(Exception exc) {
				MessageBox.Show(this,exc.ToString());
			}
		} 
		#endregion

		#region Image Processing
		private void BProcessImage_Click(object sender,System.EventArgs e) {
			if(!bProcessImage) {
				bProcessImage = true;
				bFinishFlag = false;
				BProcessImage.Text = "Cancel";
				if(!VSTwain1.DespeckleImage(imageNum,8,25,30,400))
					MessageBox.Show(VSTwain1.errorString);
				else {
					if(!VSTwain1.DeskewImage(imageNum,BorderColor.AutoDetect))
						MessageBox.Show(VSTwain1.errorString);
					else {
						if(!VSTwain1.DetectImageBorder(imageNum,5))
							MessageBox.Show(VSTwain1.errorString);
						else {
							if(pictureBox1.Image != null) {
								pictureBox1.Image.Dispose();
								pictureBox1.Image = null;
							}
							labelImgNum.Text = "Image " + imageNum.ToString() + " (" + VSTwain1.GetImageWidth(imageNum).ToString() + " x " + VSTwain1.GetImageHeight(imageNum).ToString() + " x " + VSTwain1.GetImageBPP(imageNum).ToString() + " bpp)";
							pictureBox1.Image = VSTwain1.GetImage(imageNum);
						}
					}
				}
			} else {
				bFinishFlag = true;
			}
			bProcessImage = false;
			BProcessImage.Text = "Despeckle => deskew => detect border";
		}

		private void ImageProcessing_Progress(object sender,VintaSoft.Twain.ProgressEventArgs e) {
			if(e.Action == Action.Deskew) txtAction.Text = "Deskewing...";
			else if(e.Action == Action.Despecle) txtAction.Text = "Despeckling...";
			else if(e.Action == Action.BorderDetection) txtAction.Text = "Border detecting...";
			else if(e.Action == Action.Rotation) txtAction.Text = "Rotating...";
			progressBar1.Value = (int)e.PercentComplete;
			e.Interrupt = bFinishFlag;
		}

		bool bFinishFlag = false;
		bool bProcessImage = false;

		int rotationAngle = 90;

		private void BRotateImage_Click(object sender,System.EventArgs e) {
			VSTwain1.rotation = rotationAngle;
			rotationAngle += 90; if(rotationAngle == 360) rotationAngle = 0;
			if(pictureBox1.Image != null) {
				pictureBox1.Image.Dispose();
				pictureBox1.Image = null;
			}
			labelImgNum.Text = "Image " + imageNum.ToString() + " (" + VSTwain1.GetImageWidth(imageNum).ToString() + " x " + VSTwain1.GetImageHeight(imageNum).ToString() + " x " + VSTwain1.GetImageBPP(imageNum).ToString() + " bpp)";
			pictureBox1.Image = VSTwain1.GetImage(imageNum);

		} 
		#endregion

		private void txtBarCode_Validated(object sender, EventArgs e) {
			if( ((TextBox)sender).Text == "" )return;
			dsBarCodes.BarCode.AddBarCodeRow(((TextBox)sender).Text, 0, "");
			lblBarCodes.Text = dsBarCodes.GetXml();
			((TextBox)sender).Text = "";
		}

		private void btnStop_Click(object sender,EventArgs e) {
			AutoCrop();
			//VSTwain1.Acquire();
			//VSTwain1.SetImageLayout(0,0,1,1);
			//VSTwain1.CloseDataSource();
		}

		private void btnSaveTo_Click(object sender,EventArgs e) {
			fbd.ShowNewFolderButton = true;
			fbd.SelectedPath = SaveTo;
			if(fbd.ShowDialog(this) == DialogResult.Cancel) return;
			SaveTo = fbd.SelectedPath;
		}

		private void txtSaveTo_ControlAdded(object sender,ControlEventArgs e) {
			((Control)sender).Text = SaveTo;
		}

		private void MainForm_Load(object sender,EventArgs e) {
			SaveTo = SaveTo;
			txtBarCode.Focus();
		}

		private void MainForm_FormClosing(object sender,FormClosingEventArgs e) {
			Settings.Save();
		}

		private void txtSaveTo_TextChanged(object sender,EventArgs e) {
			Settings.SaveTo = ((TextBox)sender).Text;
		}

		void SendTab(object sender,EventArgs e) {
			txtBarCode.Focus();
			SendKeys.SendWait("{TAB}");
		}
		private void txtBarCode_PreviewKeyDown(object sender,PreviewKeyDownEventArgs e) {
			if(e.KeyCode == Keys.Enter) txtBarCode.Invoke(new EventHandler(SendTab));
			if(e.KeyCode == Keys.S && e.Control) BSaveImage_Click(null,null);
			if(e.KeyCode == Keys.Down) pmDate.Value = pmDate.Value.AddDays(1);
			if(e.KeyCode == Keys.Up) pmDate.Value = pmDate.Value.AddDays(-1);
		}

		void SetFocus(object sender,EventArgs e) {
			((TextBox)sender).Focus();
		}
		private void txtBarCode_Leave(object sender,EventArgs e) {
			//((TextBox)sender).Invoke(new EventHandler(SetFocus));
		}

		private void timerBarCodeBox_Tick(object sender,EventArgs e) {
			txtBarCode.Invoke(new EventHandler(SetFocus));
		}

		private void timerStopScanner_Tick(object sender,EventArgs e) {
			//VSTwain1.CloseDataSource();
			timerStopScanner.Stop();
		}

	}
}
